package com.zzgc.modules.controller;

import com.zzgc.common.entity.AuthDepart;
import com.zzgc.common.entity.AuthRole;
import com.zzgc.common.entity.AuthUser;
import com.zzgc.common.entity.AuthUserRole;
import com.zzgc.common.fliter.StatelessRealm;
import com.zzgc.common.response.HttpStatus;
import com.zzgc.common.response.Result;
import com.zzgc.common.utils.JWTUtil;
import com.zzgc.common.utils.MD5Util;
import com.zzgc.common.utils.StringUtils;
import com.zzgc.modules.log.ApiLog;
import com.zzgc.modules.param.AuthUserSchoolParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;
import java.util.*;

/**
 * 用户管理模块
 * @Author:
 * @CreateTime: 2022-12-19  15:53
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("auth/user")
@ApiLog(value = "用户管理模块类", url = "auth/user")
@Api(tags = "用户控制")
public class AuthUserController extends BaseController{

    @PostMapping("login")
    @ApiLog(value = "用户登陆", url = "login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登陆", notes = "JSON格式数据,传输字段: aAccount/aPassword")
    public Result login(@RequestBody AuthUser authUser){
        // System.out.println("authUser = " + authUser);
        // 校验账户与密码, 可能抛出错误, 直接返回前端
        AuthUser user = verifyAccountAndPassword(authUser.getAAccount(), authUser.getAPassword());
        // 生成token并返回
        String tokenStr = null;
        try {
            tokenStr = makeTokenStrAndRecordTime(user);
        } catch (Exception e) {
            throw new RuntimeException("登录异常!");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("token", tokenStr);
        data.put("userId", user.getId());
        data.put("userName", user.getAName());
        data.put("role", JWTUtil.resolveClaim(tokenStr, "role"));
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(data)
                .build();
    }
    /**
     * 添加token信息
     *
     * @param user
     * @return
     */
    private String makeTokenStrAndRecordTime(AuthUser user) throws Exception {
        // 查询角色信息
        AuthUserRole authUserRole = userRoleService.queryByUserId(user.getId());
        // 查询角色类型
        AuthRole authRole = super.roleService.queryById(authUserRole.getARoleId());
        // 查询部门
        AuthDepart authDepart = departService.queryById(user.getADepartId());
        Map<String, String> payload = new HashMap<>();
        payload.put("userName", user.getAName());
        payload.put("userId", user.getId() + "");
        payload.put("schoolId", user.getASchoolId() == null ? null : user.getASchoolId() + "");
        payload.put("aDepartId", user.getADepartId() == null ? null : user.getADepartId() + "");
        payload.put("regionId", authDepart.getARegionId() == null ? null : authDepart.getARegionId() + "");
        payload.put("role", authUserRole.getARoleId() == null ? null : authUserRole.getARoleId() + "");// 角色信息
        // 角色类型 1：系统角色 2：普通角色
        payload.put("type", authRole.getAType() == 1 ? StatelessRealm.ADMIN_AUTHENTICATION : StatelessRealm.USER_AUTHENTICATION);// 用户类型
        // 记录登录时间
        //uUserService.updateUUserLoginTime(user.getUserName(), loginTime);
//        return JWTUtil.getToken(payload,20); 不添加时间默认720分钟
        return JWTUtil.getToken(payload);
    }

    /**
     * 校验用户的登录account与password</br>
     * 若校验通过，返回包含着用户信息的JavaBean对象</br>
     *
     * @param username
     * @param password
     * @return
     */
    private AuthUser verifyAccountAndPassword(String username, String password) {
        // 获取用户信息
        AuthUser authUser = new AuthUser();
        authUser.setAAccount(username);
        authUser.setSize(Integer.MAX_VALUE);
        List<AuthUser> authUsers = userService.queryByPage(authUser);
        //System.out.println(authUsers.getTotalElements());

        if (authUsers.size() == 0) {
            throw new RuntimeException(HttpStatus.NOT_REGISTER.value() + "#-#" + HttpStatus.NOT_REGISTER.getReasonPhrase());
        } else if (authUsers.size() > 1) {
            throw new RuntimeException(HttpStatus.NOT_REGISTER.value() + "#-#存在多个账户!");
        } else if (!authUsers.get(0).getAPassword().equals(MD5Util.getMD5PWD(password))) {
            throw new RuntimeException(HttpStatus.USERNAME_OR_PASSWORD_ERROR.value() + "#-#" + HttpStatus.USERNAME_OR_PASSWORD_ERROR.getReasonPhrase());
        } else if (authUsers.get(0).getABankStatus().equals("1")) {
            throw new RuntimeException( "401#-#账户被锁定请联系管理员！" );
        }
        return authUsers.get(0);
    }

    @GetMapping("get/departs")
    @ApiLog(value = "获取部门分级列表", url = "get/departs", method = RequestMethod.GET)
    @ApiOperation(value = "获取部门分级列表", notes = "获取部门分级列表")
    public Result getDepartList(Long departId) {
        if (StringUtils.isNull(departId)) {
            departId = Long.valueOf(super.getDepartId() == null ? "1" : super.getDepartId());
        }
        // 获取多级部门信息
        AuthDepart authDepart = departService.queryById(departId);
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(authDepart).build();
    }



    @GetMapping("get/district")
    @ApiLog(value = "获取区县部门列表", url = "get/district", method = RequestMethod.GET)
    @ApiOperation(value = "获取区县部门列表", notes = "获取区县部门列表")
    public Result getDistrictList(String city, String district, Long districtId){
        String userRole = super.getUserRole();
        //判断是否是河南省教育局
        if (!userRole.equals("1") && !userRole.equals("2")) {
            String dist =super.getDepartId();
            AuthDepart depart = departService.queryById(Long.parseLong(dist));
            city = depart.getAIdBak();
            if (districtId.equals(Long.valueOf(1))) {
                districtId = depart.getId();
            }
        }
        AuthDepart authDepart = new AuthDepart();
        authDepart.setAIdBak(district);
        authDepart.setAParentId(districtId);
        System.out.println(districtId);
        authDepart.setAParentIdBak(city);
        if (StringUtils.isNull(districtId)) {
            authDepart.setAParentId(Long.valueOf(super.getDepartId()));
        }else {
            authDepart.setAParentId(districtId);

        }
        //authDepart.setALevel(3);
        authDepart.setSize(Integer.MAX_VALUE);
        List<AuthUser> authUsers = userService.queryByDepart(authDepart);
        Map<String, Object> hashMap = new HashMap<>();
        // 添加部门信息
        for (AuthUser authUser : authUsers) {
            if (StringUtils.isNull(authUser.getADepartId())) {
                authUser.setDepartName("系统管理员");
            }else {
                authUser.setDepartName(departService.queryById(authUser.getADepartId()).getAName());
            }
        }
        hashMap.put("total", authUsers.size() == 0 ? 0 : authUsers.get(0).getTotal());
        hashMap.put("data", authUsers);
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(hashMap).build();
    }

    @PostMapping("add/district")
    @ApiLog(value = "添加区县部门", url = "add/district", method = RequestMethod.POST)
    @ApiOperation(value = "添加区县部门", notes = "添加区县部门")
    public Result addUserDistrict(@RequestBody AuthUserSchoolParam schoolParam) {
        // 校验手机号和账号, 校验重复值
        List<AuthUser> authUsers = userService.queryAllByNamePwd(schoolParam.getAccount(), schoolParam.getMobile());
        if (authUsers.size() > 0) { // 用户名已存在
            return Result.builder().code(500).msg("用户名或手机号已占用!").build();
        }
        // 检查是否存在市级部门
        AuthDepart authDepart = new AuthDepart();
        authDepart.setAIdBak(schoolParam.getCity());
        authDepart.setALevel(2);
        List<AuthDepart> authDeparts = departService.queryByPage(authDepart);
        if (StringUtils.isEmpty(authDeparts)) {
            return Result.builder().code(500).msg("您还没有添加市级平台，不能添加县级！").build();
        }
        // 检查是否存在县级部门和用户
        authDepart.setAIdBak(schoolParam.getDistrict());
        authDepart.setAParentIdBak(schoolParam.getCity());
        authDepart.setALevel(3);
        List<AuthDepart> authDeparts1 = departService.queryByPage(authDepart);
        if (StringUtils.isNotEmpty(authDeparts1)) {
            return Result.builder().code(500).msg("已存在该区县管理员,不能重复添加").build();
        }
        // 添加区县部门
        AuthUserSchoolParam authUserSchoolParam = userService.insertUserDepart(schoolParam);
        // 添加区县用户
        return Result.builder().code(HttpStatus.OK.value())
                .msg("账号添加成功, 用户默认密码为：123456").data(authUserSchoolParam).build();
    }

    @GetMapping("get")
    @ApiLog(value = "获取用户信息", url = "get", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    public Result getUserInfo(Long id) {
        AuthUser authUser = userService.queryById(id);
        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase())
                .data(authUser).build();
    }

    @PutMapping("edit/district")
    @ApiLog(value = "修改区县部门信息", url = "edit/district", method = RequestMethod.PUT)
    @ApiOperation(value = "修改区县部门信息", notes = "修改区县部门信息")
    public Result editDistrict(@RequestBody AuthUserSchoolParam schoolParam) {
        boolean b = false;
        if (StringUtils.isNull(schoolParam.getUserId())) {
            b = true;
        }
        if (StringUtils.isEmpty(schoolParam.getAccount())) {
            b = true;
        }
        if (StringUtils.isEmpty(schoolParam.getMobile())) {
            b = true;
        }
        if (StringUtils.isEmpty(schoolParam.getName())) {
            b = true;
        }
        if (b){
            return Result.builder().code(500).msg("请求参数有误！").build();
        }

        // 校验手机号和账号, 校验重复值
        List<AuthUser> authUsers = userService.queryAllByNamePwd(schoolParam.getAccount(), schoolParam.getMobile());
        if (authUsers.size() > 0) {
            if (authUsers.size() == 1) { // 判断是否是自己
                if (authUsers.get(0).getId() != schoolParam.getUserId()) {
                    return Result.builder().code(500).msg("用户名或手机号已占用!").build();
                }
            }else {
                return Result.builder().code(500).msg("用户名或手机号已占用!").build();
            }
        }
        AuthUser authUser = new AuthUser();
        authUser.setId(schoolParam.getUserId());
        authUser.setAName(schoolParam.getName());
        authUser.setAAccount(schoolParam.getAccount());
        authUser.setAMobile(schoolParam.getMobile());
        authUser.setAUpdateDate(new Date());
        userService.update(authUser);

        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase())
                .data(schoolParam).build();
    }

    @GetMapping("onOff")
    @ApiLog(value = "启用和禁用用户", url = "onOff", method = RequestMethod.GET)
    @ApiOperation(value = "启用和禁用用户", notes = "启用和禁用用户")
    public Result onAndOff(Long id) {
        if (StringUtils.isNull(id)) {
            return Result.builder().code(500).msg("请求参数有误！").build();
        }
        AuthUser authUser = userService.queryById(id);
        if (authUser.getABankStatus().equals("0")) { // 如果是启用，就禁掉
            authUser.setABankStatus("1");
            userService.update(authUser);
        }else {// 否则就启用
            authUser.setABankStatus("0");
            userService.update(authUser);
        }
        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase()).build();
    }

    @DeleteMapping("del")
    @ApiLog(value = "删除区县用户", url = "del", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除区县用户", notes = "删除区县用户")
    public Result delUser(Long id) {
        if (!userService.deleteById(id)) {
            return Result.builder().code(500).msg("删除失败！").build();
        }
        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase()).build();
    }

    @PostMapping("edit/pwd")
    @ApiLog(value = "修改用户密码", url = "edit/pwd", method = RequestMethod.POST)
    @ApiOperation(value = "修改用户密码", notes = "修改用户密码")
    public Result delUser(String oldPwd, String newPwd) {
        AuthUser authUser = userService.queryById(Long.valueOf(super.getUserId()));
        if (!authUser.getAPassword().equals(MD5Util.getMD5PWD(oldPwd))){
            return Result.builder().code(500).msg("密码错误").build();
        }
        authUser.setAPassword(MD5Util.getMD5PWD(newPwd));
        authUser.setAUpdateDate(new Date());
        userService.update(authUser);
        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase())
                .data(authUser).build();
    }



}
